
<template>
  <el-dialog top="80px"
    :visible.sync="isVisible"
    :title="title"
    width="920px"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-container>
      <el-main v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main">
        <el-form ref="elForm"
          size="small"
          label-position="right"
          :model="form"
          :rules="rules"
          label-width="120px">
          <div>
            <div class="title">
              <span>填写信息</span>
            </div>
            <el-card class="card"
              shadow="never"
              style="background: #fafafa; ">
              <div style="margin-left: -12px; margin-right: -12px">
                <el-row>
                  <el-col :span="23">
                    <el-form-item label="通讯类型"
                      prop="communicationType">
                      <el-select v-model="form.communicationType"
                        popper-class="global-select"
                        placeholder="选择通讯类型"
                        clearable
                        filterable
                        :disabled="operationType == 'detail'">
                        <el-option v-for="item in communicationTypeList"
                          :key="item.dictValue"
                          :label="item.dictText"
                          :value="item.dictValue" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="23">
                    <el-form-item label="关联网关"
                      prop="isLinkGateway">
                      <el-radio-group v-model="form.isLinkGateway"
                        :disabled="operationType == 'detail'"
                        @change="onIsLinkGatewayChange($event)">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="23">
                    <el-form-item label="编码前缀"
                      prop="prefixCode">
                      <el-input v-model="form.prefixCode"
                        placeholder="输入编码前缀"
                        clearable
                        :disabled="form.isLinkGateway || operationType == 'detail'" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="23">
                    <el-form-item label="适用对象"
                      prop="ruleTarget">
                      <el-transfer filterable
                        v-model="form.ruleTarget"
                        :titles="['设备类型', '规则对象']"
                        :button-texts="['移除对象', '添加对象']"
                        :props="{
                          key: 'dictValue',
                          label: 'dictText'
                        }"
                        @change="handleChange"
                        :data="deviceTypeList">
                      </el-transfer>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </div>
        </el-form>
      </el-main>

      <el-footer>
        <el-button size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="toClose">
          取消
        </el-button>
        <el-button size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit">
          {{ params.item.id == -1 ? "提交" : "修改" }}
        </el-button>
      </el-footer>
    </el-container>
  </el-dialog>
</template>
<script>
import dataFormMixins from "@/mixins/data-form-mixins";
import deviceManageApi from "@/api/device-manage";

export default {
  name: "EquipmentCodeRuleAdd",
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    params: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data () {
    return {
      communicationTypeList: [],
      deviceTypeList: [],
      operationType: ''
    };
  },
  computed: {
    isVisible: {
      get () {
        return this.dialogVisible;
      },
      set () {
        this.toClose();
      }
    }
  },
  mounted () {
    this.operationType = this.params.operationType
    this.rules = this.initRules();
    this.form = this.initForm();

    this.getCommunicationTypeList()
    this.getDeviceTypeList()

    if (this.params.item.id !== -1) {
      this.getDetail();
    }
  },
  methods: {
    initRules () {
      return {
        communicationType: this.getValidatorForm("change"),
        isLinkGateway: this.getValidatorForm("change"),
        ruleTarget: this.getValidatorForm("change"),
      };
    },
    initForm () {
      return {
        id: "",
        communicationType: '', // 通讯类型
        isLinkGateway: '',  // 是否关联网关
        prefixCode: "", // 编码前缀
        ruleTarget: [], // 适用对象
      };
    },
    getCommunicationTypeList () {
      const data = {
        fieldName: "communication_type",
        tableName: "t_communication"
      };
      deviceManageApi.getDictValueAttr(data).then(r => {
        this.communicationTypeList = r.data.dictValue;
      });
    },
    getDeviceTypeList () {
      const data = {
        fieldName: "collect_type",
        tableName: "t_equipment_collect"
      };
      deviceManageApi.getDictValueAttr(data).then(ret => {
        this.deviceTypeList = ret.data.dictValue;
        if (this.operationType == 'detail') {
          this.deviceTypeList.forEach((ele) => {
            ele.disabled = true
          })
        }

      });
    },
    getDetail () {
      this.loading = true;
      deviceManageApi
        .getEquipmentCodeRuleFindById({ id: this.params.item.id })
        .then(ret => {

          this.detailObj = ret.data.data;
          this.form = { ...this.detailObj };

          const list = []
          this.detailObj.ruleTarget.split(',').forEach((ele) => {
            list.push(Number(ele))
          })
          this.form.ruleTarget = list
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleChange (value, direction, movedKeys) {
    },
    onIsLinkGatewayChange (event) {
      if (event) {
        this.form.prefixCode = ''
      }
    },
    toClose () {
      this.$emit("close");
    },
    toSubmit () {
      this.$refs.elForm.validate(valid => {
        if (valid) {
          const model = {};
          Object.keys(this.form).forEach((key) => {
            model[key] = this.form[key]
          })
          model.ruleTarget = model.ruleTarget.toString()
          // console.log('model=', model)
          if (this.params.item.id === -1) {
            deviceManageApi
              .addEquipmentCodeRule(model)
              .then(ret => {
                this.submitLoading = false;
                this.isVisible = false;
                this.$message({
                  message: "提交成功！",
                  type: "success"
                });
                this.$emit("submit", "add");
              })
              .catch(() => {
                this.submitLoading = false;
              });
          } else {
            deviceManageApi
              .updateEquipmentCodeRule(model)
              .then(ret => {
                this.submitLoading = false;
                this.isVisible = false;
                this.$message({
                  message: "修改成功！",
                  type: "success"
                });
                this.$emit("submit", "edit");
              })
              .catch(() => {
                this.submitLoading = false;
              });
          }
        } else {
          this.$message({
            message: "*必填项不能为空！",
            type: "warning",
            duration: 4000
          });
          return false;
        }
      })
    },
  },
};
</script>

<style lang='scss' scoped>
@import "../../../../../styles/part-custom";
</style>
